//
//  ClassViewController.m
//  Product_NEWS
//
//  Created by dllo on 16/1/4.
//  Copyright © 2016年 FCH. All rights reserved.
//
#define WIDTH                    ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT                   ([UIScreen mainScreen].bounds.size.height)
#import "ClassViewController.h"
#import "VideoViewCell.h"
#import "VideoData.h"
#import "DetailViewController.h"
#import "UMSocialSnsPlatformManager.h"
#import "UMSocialSnsService.h"
#import <AVFoundation/AVFoundation.h>

@interface ClassViewController ()<UITableViewDataSource,UITableViewDelegate,VideoPlayDelegate>
@property(nonatomic,retain)NSMutableArray *videoArray;
@property(nonatomic,retain)UITableView *myTableView;
@property(nonatomic,assign)int page;
@property(nonatomic,assign)BOOL isUpLoading;

@property (nonatomic, retain) UILabel *leftTimeLabel;
@property (nonatomic, retain) UILabel *rightTimeLabel;


// 设置播放器播放项目的类， 播放视频资源
@property (nonatomic, retain) AVPlayerItem *playerItem;
// 视频播放器对象
@property (nonatomic, retain) AVPlayer *player;
//  设置承载显示视频播放器的类
@property (nonatomic, retain) AVPlayerLayer *playerLayer;
@property (nonatomic, retain) UIView *btnView;
@property (nonatomic ,retain) UIButton *playButton;
@property (nonatomic, retain) UIView *playerView;
@property (nonatomic, retain) UISlider *slider;

@property (nonatomic, assign) CGFloat totalDuraion; // 记录总时长

@property (nonatomic ,assign) BOOL isPlaying; // 记录播放状态



@end

@implementation ClassViewController
- (NSMutableArray *)videoArray {
    if (!_videoArray) {
        self.videoArray = [NSMutableArray array];
    }
    return [[_videoArray retain] autorelease];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   

    [self initUI];
    [self addHeader];
    [self addFooter];
    
    
}

-(void)initUI{
     self.view.backgroundColor = [NightModeHandle shareNightModeHandle].allViewColor;
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 375, 10 * SCREEN_WIDTH )];
    
    view1.backgroundColor = [NightModeHandle shareNightModeHandle].allViewColor;
    [self.myTableView addSubview:view1];
    self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(10 *SCREEN_WIDTH, 0, 355 * SCREEN_WIDTH, 657 * SCREEN_HEIGHT) style:UITableViewStyleGrouped];
     _myTableView.delegate = self;
     _myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    _myTableView.tableHeaderView = view1;
}


//刷新

-(void)addHeader
{
    __block ClassViewController *vc = self;
    
    [self.myTableView addHeaderWithCallback:^{
        vc.page = 1;
        vc.isUpLoading = NO;
        [vc GetPersonList:vc.page];

        
    }];
    [self.myTableView headerBeginRefreshing];
}

-(void)addFooter
{
    __block ClassViewController *vc = self;
    [self.myTableView addFooterWithCallback:^{
        vc.page ++;
        vc.isUpLoading = YES;
        [vc GetPersonList:vc.page];
    }];
}
-(void)GetPersonList:(NSInteger)nextCursor
{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    
    NSString *getstr = [NSString stringWithFormat:@"http://c.3g.163.com/nc/video/list/%@/y/%d-10.html",_url,self.page];

   
    
    
    [mgr GET:getstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.videoArray removeAllObjects];
        }
        NSMutableArray *allArr = [responseObject objectForKey:_url];
        for (NSDictionary *dic in allArr) {
            
            VideoData *videoData = [[VideoData alloc]init];
            [videoData setValuesForKeysWithDictionary:dic];
            
            videoData.Description = [dic objectForKey:@"description"];
            
            
            [self.videoArray addObject:videoData];
          
        }
        
        
        
        //        self.page += 10;
        // 刷新表格
        [self.myTableView footerEndRefreshing];
        [self.myTableView headerEndRefreshing];
        [self.myTableView reloadData];
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.mode = MBProgressHUDModeText;
        mb.labelText = @"网络不给力呀";
        [mb hide:YES afterDelay:0.5];
        [self.myTableView headerEndRefreshing];
        [self.myTableView footerEndRefreshing];

    }];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videoArray.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    VideoViewCell *cell = [VideoViewCell cellWithTableView:tableView];
    cell.myDelegate = self;
    VideoData *video = self.videoArray[indexPath.row];
    cell.videoData = video;
    cell.indexPath = indexPath;
    return cell;

    
}

  // 点击
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 300*SCREEN_HEIGHT;
}

#pragma mark -- Delegate

-(void)videoPlay:(NSIndexPath *)indexPath
{
   
    VideoData *model = self.videoArray[indexPath.row];
    [self playWithUrl:model.mp4_url];
   
    self.playerView.frame = CGRectMake(0, 10 * SCREEN_HEIGHT + 300 * SCREEN_HEIGHT * indexPath.row  , 375 * SCREEN_WIDTH,375 * SCREEN_WIDTH * 0.5);
    self.playerLayer.frame = self.playerView.bounds;
    
    [self showPlayerProgress];
    [self.player play];
    
}

-(void)shareVideo:(NSIndexPath *)indexPath{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    /**
     Sns平台类，用`platformName`作为标识，指定显示名称、显示的图片，点击之后的响应。
     */
    snsPlatform.displayName = @"新浪";
    snsPlatform.loginName = @"网易";
    
    
    UMSocialSnsPlatform *snsPlatform2 = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToTencent];
    snsPlatform2.displayName = @"腾讯微博";
    
    
    
    //分享第二步
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"558936d367e58eb81b001298"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"Icon-29.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:nil];
}
-(void)VideoCommon:(NSIndexPath *)indexPath{
    VideoData *model = self.videoArray[indexPath.row];
    
    DetailViewController *detail = [[DetailViewController alloc]init];
    detail.model = model;
    [self.navigationController pushViewController:detail animated:YES];
}




#pragma 设置视频相关

- (void)playWithUrl:(NSString *)urlString{
    
    NSURL *url = [NSURL URLWithString:urlString];
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    if (_player == nil) {
        
        self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
        self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        self.playerLayer.frame = self.playerView.bounds;
        [self.playerView.layer addSublayer:self.playerLayer];
        
        
        self.btnView = [[UIView alloc] initWithFrame:CGRectMake(0,self.playerView.frame.size.height - 30 * SCREEN_HEIGHT + 185 * SCREEN_HEIGHT, 375 * SCREEN_WIDTH, 30 * SCREEN_HEIGHT)];
        self.btnView.backgroundColor = [UIColor blackColor];
        self.btnView.alpha = 0.5;
        [self.playerView addSubview:self.btnView];
        [_btnView release];
        
        self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.playButton.frame = CGRectMake(5 * SCREEN_WIDTH, 5*SCREEN_HEIGHT, 15* SCREEN_WIDTH, 15*SCREEN_HEIGHT);
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
        [self.playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.btnView addSubview:self.playButton];
        [_playButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        self.slider = [[UISlider alloc] initWithFrame:CGRectMake(90* SCREEN_WIDTH, 3 * SCREEN_HEIGHT, 200* SCREEN_WIDTH, 20* SCREEN_HEIGHT)];
        self.slider.value = 0;
        self.slider.maximumValue = 1;
        self.slider.minimumValue = 0;
        
        
        self.leftTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(40 * SCREEN_WIDTH, -10 *SCREEN_HEIGHT, 50* SCREEN_WIDTH, 50*SCREEN_HEIGHT)];
        self.leftTimeLabel.font = [UIFont systemFontOfSize:13 * SCREEN_WIDTH];
        self.leftTimeLabel.textColor = [UIColor whiteColor];
        self.leftTimeLabel.text = @"00:00";
        [self.btnView addSubview:self.leftTimeLabel];
        
        
        self.rightTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(300 * SCREEN_WIDTH, -10* SCREEN_HEIGHT, 50 * SCREEN_WIDTH, 50* SCREEN_HEIGHT)];
        self.rightTimeLabel.textColor = [UIColor whiteColor];
        self.rightTimeLabel.text = @"00:00";
        self.rightTimeLabel.font = [UIFont systemFontOfSize:13 * SCREEN_WIDTH];
        [self.btnView addSubview:self.rightTimeLabel];
        
        
        [self.btnView addSubview:self.slider];
        [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
        [_slider release];
        
        self.isPlaying = NO;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        
        [self.playerView addGestureRecognizer:tap];
        
        
    }else{
        
        [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
    }
    //    }
    self.isPlaying = YES;
    
}

//视频左下方播放按钮
- (void)buttonAction:(UIButton *)button{
    
    if (self.isPlaying == NO) {
        [self.player play];
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
        
    }else{
        
        [self.player pause];
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-bofangqibofang.png"] forState:UIControlStateNormal];
    }
    self.isPlaying = !self.isPlaying;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:2 animations:^{
                
                self.btnView.alpha = 0;
            }];
            
        });
        
    });
}


//滑动条
- (void)sliderAction:(UISlider *)slider{
    
    
    double currentTime = slider.value * self.totalDuraion;
    
    CMTime time = CMTimeMake(currentTime, 1);
    
    [self.player seekToTime:time completionHandler:^(BOOL finished) {
        
        [self.player play];
        
    }];
    
    
}

- (void)showPlayerProgress{
    
    CMTime time = CMTimeMake(1, 1);
    
    
    __block ClassViewController *vc = self;
    
    [vc.player addPeriodicTimeObserverForInterval:time queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        CMTime currentTime = vc.playerItem.currentTime;
        CMTime totalTime = vc.playerItem.duration;
        
        double currentT = CMTimeGetSeconds(currentTime);
        double totalT = CMTimeGetSeconds(totalTime);
        
        vc.slider.value = currentT / totalT;
        
        vc.totalDuraion = totalT;
        
        
        
        // 总时长
        CGFloat duration = CMTimeGetSeconds(self.playerItem.duration);
        
        // 当前时长
        CGFloat current = CMTimeGetSeconds(self.player.currentTime);
        
        
        NSString *duration1 = [NSString stringWithFormat:@"%02d:%02d", (int)duration / 60, (int) duration % 60];
        NSString *currentTime1 = [NSString stringWithFormat:@"%02d:%02d", (int) current / 60, (int) current % 60];
        
        self.leftTimeLabel.text = currentTime1;
        self.rightTimeLabel.text = duration1;
        
        
    }];
    
}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    
    if (self.btnView.alpha == 1) {
        [UIView animateWithDuration:1 animations:^{
            
            self.btnView.alpha = 0;
        }];
    }else{
        [UIView animateWithDuration:1 animations:^{
            
            self.btnView.alpha = 0;
        }];
    }
    
}




- (UIView *)playerView{
    if (nil == _playerView) {
        _playerView = [[UIView alloc] init];
        [_myTableView addSubview:self.playerView];
    }
    return _playerView;
}


-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (self.playerLayer) {
        NSLog(@"销毁了");
        [self.player pause];
        [self.playerView removeFromSuperview];
        self.player = nil;
    }
 
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
